-- region *.lua
-- Date
-- 此文件由[BabeLua]插件自动生成

-- ****************************************
-- 定义MPU6050内部地址
-- ****************************************
SMPLRT_DIV = 0x19	-- 陀螺仪采样率，典型值：0x07(125Hz)
CONFIG = 0x1A	-- 低通滤波频率，典型值：0x06(5Hz)
GYRO_CONFIG = 0x1B	-- 陀螺仪自检及测量范围，典型值：0x18(不自检，2000deg/s)
ACCEL_CONFIG = 0x1C	-- 加速计自检、测量范围及高通滤波频率，典型值：0x01(不自检，2G，5Hz)
ACCEL_XOUT_H = 0x3B
ACCEL_XOUT_L = 0x3C
ACCEL_YOUT_H = 0x3D
ACCEL_YOUT_L = 0x3E
ACCEL_ZOUT_H = 0x3F
ACCEL_ZOUT_L = 0x40
TEMP_OUT_H = 0x41
TEMP_OUT_L = 0x42
GYRO_XOUT_H = 0x43
GYRO_XOUT_L = 0x44
GYRO_YOUT_H = 0x45
GYRO_YOUT_L = 0x46
GYRO_ZOUT_H = 0x47
GYRO_ZOUT_L = 0x48
PWR_MGMT_1 = 0x6B	-- 电源管理，典型值：0x00(正常启用)
WHO_AM_I = 0x75	-- IIC地址寄存器(默认数值0x68，只读)
SlaveAddress = 0xD0	-- IIC写入时的地址字节数据，+1为读取

id = 0

function write(regaddr, regdata)
    i2c.start(id)
    i2c.address(id, 0x68, i2c.TRANSMITTER)
    i2c.write(id, regaddr)
    i2c.write(id, regdata)
    i2c.stop(id)
end 

function read(regaddr)
    i2c.start(id)
    i2c.address(id, 0x68, i2c.TRANSMITTER)
    i2c.write(id, regaddr)
    i2c.start(id)
    i2c.address(id, 0x68, i2c.RECEIVER)
    regdata = i2c.read(id, 1)
    i2c.stop(id)
    return tonumber(string.byte(regdata))
end

function getdata(regaddr)
    H = read(regaddr)
    L = read(regaddr+1)
    print(H,L)
    return bit.lshift(H, 8) + L
end


sda = 1
scl = 2

-- initialize i2c, set pin1 as sda, set pin2 as scl
i2c.setup(id, sda, scl, i2c.SLOW)


write(PWR_MGMT_1, 0x00);	-- 解除休眠状态
write(SMPLRT_DIV, 0x07);
write(CONFIG, 0x06);
write(GYRO_CONFIG, 0x18);
write(ACCEL_CONFIG, 0x01);



tmr.alarm(1, 1000, 1, function()
    print("xa=", getdata(ACCEL_XOUT_H), "ya=", getdata(ACCEL_YOUT_H), "za=", getdata(ACCEL_ZOUT_H), "xg=", getdata(GYRO_XOUT_H), "yg=", getdata(GYRO_YOUT_H), "zg=", getdata(GYRO_ZOUT_H))
end )


-- endregion
